package leetcode.offer_two_special.tree;

import leetcode.tree.common.TreeNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author mazouri
 * @create 2021-09-11 23:02
 */
public class Codec {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "#";

        return root.val +","+serialize(root.left)+","+serialize(root.right);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Queue<String> strList = new LinkedList<>(Arrays.asList(data.split(",")));
        return dfs(strList);
    }

    private TreeNode dfs(Queue<String> strList) {
        String str = strList.poll();

        if ("#".equals(str)) return null;

        TreeNode node = new TreeNode(Integer.parseInt(str));
        node.left = dfs(strList);
        node.right = dfs(strList);
        return node;
    }

}
